package com.xieteng.controller;

import com.xieteng.entity.User;
import com.xieteng.service.UserService;
import com.xieteng.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 生成验证码图片
     */
    @GetMapping("/getImage")
    public String getImage(HttpServletRequest request) throws IOException {
        //使用工具类生产验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //将生成好的验证码放入servletContext作用域中
        request.getServletContext().setAttribute("code", code);
        //将验证码转换为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(80, 30, byteArrayOutputStream, code);
        String base64 = Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
        return "data:image/png;base64," + base64;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user, String code, HttpServletRequest request) {
        log.info("用户信息：[{}]", user.toString());
        log.info("用户输入的验证码：[{}]", code);
        Map<String, Object> map = new HashMap<>();
        String originCode = (String) request.getServletContext().getAttribute("code");
        try {
            if (originCode.equalsIgnoreCase(code)) {
                userService.save(user);
                map.put("status", true);
                map.put("msg", "提示：注册成功!");
            } else {
                throw new RuntimeException("验证码输入错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", false);
            map.put("msg", "提示：" + e.getMessage());
        }
        return map;
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        log.info("用户登录信息：[{}]", user.toString());
        Map<String, Object> map = new HashMap<>();
        try {
            User user1 = userService.login(user);
            if (user1 != null) {
                map.put("status", true);
                map.put("msg", "登录成功，点击确定跳转至员工信息页面");
                map.put("user", user1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", false);
            map.put("msg", "提示：" + e.getMessage());
        }
        return map;
    }
}
